const baseUrl = 'http://www.esadmin.com/api/'

const request = (options = {}) => {
	const token = uni.getStorageSync('token').token;
	const tokenExpire = uni.getStorageSync('token').expire;

	var time = Date.parse(new Date()) / 1000;

	options.header = {
		authorization: token
	}
	return new Promise((resolve, reject) => {
		
		if (tokenExpire <= time) {
			let uid = uni.getStorageSync('userInfo').id;
			uni.request({
				url: baseUrl + 'login',
				method: 'get',
				data: {
					uid
				},
				header: {
					authorization: token
				}
			}).then(data => {
				uni.setStorageSync('token', data[1].data.data.token)
				options.header = {
					authorization: data[1].data.data.token.token
				}
			})
		}
		
		uni.request({
			url: baseUrl + options.url || '',
			method: options.type || 'GET',
			data: options.data || {},
			header: options.header || {}
		}).then(data => {
			if (data[1].data.code == 302) {
				uni.showModal({
					title: '提示',
					content: '您还未登录，现在去登录吗',
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '../../pages/login/login?type=1'
							})
							return;
						} else if (res.cancel) {
							return;
						}
					}
				})
			}
			let [err, res] = data;
			resolve(res);
		}).catch(error => {
			reject(error)
		})
	});
}

const get = (url, data, options = {}) => {
	options.type = 'GET';
	options.data = data;
	options.url = url;
	return request(options)
}

const post = (url, data, options = {}) => {
	options.type = 'POST';
	options.data = data;
	options.url = url;
	return request(options)
}


export default {
	request,
	get,
	post
}
